/**
 * 检查代理是否可用，并且放到可用池
 * @constructor
 */

var request = require("request"),
    Q = require("q"),
    App = require("../common/App.js"),
    ProxyPool = require("./ProxyPool.js"),
    CheckProxy = require("./CheckProxy.js"),
    ProxyRegion = require("./ProxyRegion.js"),
    KeepAlivePool = require("./KeepAlivePool.js"),
    UsableProxyPool = require("./UsableProxyPool.js"),
    Util = require("../util/util.js");

module.exports = new CheckProxy2Pool();

function CheckProxy2Pool(){
    //单例模式
    if(typeof arguments.callee.instance === "object"){
        return arguments.callee.instance;
    }

    this.threadNum = 0;
    this.maxThreadNum = 100;

    arguments.callee.instance = this;
}
CheckProxy2Pool.prototype.start = function(){
    var that = this;
    for(var i=0;i<=500;i++){
        if(this.threadNum>this.maxThreadNum){
            continue;
        }
        var cproxy = ProxyPool.shift();
        if(cproxy==undefined){
            continue
        }
        if(UsableProxyPool.exists(cproxy)){
            console.log(cproxy.host+":"+cproxy.port+"已存在");
            continue;
        }
        console.log("正在验证:"+cproxy.host+":"+cproxy.port);

        for(var j=0;j<2;j++){
	    var proxy = Util.clone(cproxy);
            this.threadNum++;
            proxy.checkid = Util.s8();

            CheckProxy.check(proxy)//1、先检查代理是否可用
                .then(
                    function(proxy){
                        return ProxyRegion.start(proxy); //2、检查代理的地区
                    }
                )
                .then(
                    function(proxy){
                        console.log(proxy);
                        if(!isNaN(proxy.regionId)){
                            KeepAlivePool.add(proxy);
                            that.addToPool(proxy);
                        }
                        return proxy;
                    }
                )
                .then(function(proxy){
                    that.end(proxy);
                },function(err){
                    that.end(proxy);
                    console.log(err);
                });
        }

    }

}

CheckProxy2Pool.prototype.end = function(proxy){
    if(proxy!=undefined && proxy.checkid!=undefined){
        delete proxy.checkid;
        this.threadNum--;
    }
}

CheckProxy2Pool.prototype.addToPool = function(proxy){
    var deferred = Q.defer();
    try{
        var url = App.config.proxypool.add_url+"?proxy="+JSON.stringify(proxy)+"&server_ip="+App.config.serverIp;
        request.get(url,function(err,res,body_buffer){

            if(err){
                deferred.reject(err);
            }else if(res.statusCode!=200){
                deferred.reject(new Error("http status "+res.statusCode))
            }else{
                var body = body_buffer.toString();
                var rs = JSON.parse(body);
                if(rs.error!=undefined){
                    deferred.reject(new Error("res error "+rs.error));
                }else{
                    deferred.resolve();
                }
            }
        });
    }catch (e){
        deferred.reject(e);
    }
    return deferred.promise;
}
